<template>
    <div style="margin-top: 50px">
        <el-form :model="value" ref="productAttrForm" label-width="120px" class="form-inner-container" size="small">
            <el-form-item label="属性类型：">
                <el-select v-model="value.productAttributeCategoryId" placeholder="请选择属性类型" @change="handleProductAttrChange">
                    <el-option v-for="item in productAttributeCategoryOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="商品规格：">
                <el-card shadow="never" class="cardBg">
                    <div v-for="(productAttr,idx) in selectProductAttr">
                        {{productAttr.name}}:
                        <!-- 不支持手动新增的用可选值列表选取 -->
                        <el-checkbox-group v-if="productAttr.handAddStatus===0" v-model="selectProductAttr[idx].values">
                            <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :label="item" :key="item"></el-checkbox>
                        </el-checkbox-group>
                        <!-- 支持手动新增的 -->
                        <div v-else>
                            <el-checkbox-group v-model="selectProductAttr[idx].values">
                                <div v-for="(item,index) in selectProductAttr[idx].options" style="display: inline-block">
                                    <el-checkbox :label="item" :key="item"></el-checkbox>
                                    <el-button type="text" class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx,index)">删除</el-button>
                                </div>
                            </el-checkbox-group>
                            <el-input v-model="addProductAttrValue" style="width: 160px;margin-left: 10px" clearable></el-input>
                            <el-button class="littleMarginLeft" @click="handleAddProductAttrValue(idx)">增加</el-button>
                        </div>
                    </div>
                </el-card>
                <!-- sku列表显示 -->
                <el-table style="width: 100%;margin-top: 20px" :data="value.skuStockList" border>
                    <el-table-column v-for="(item,index) in selectProductAttr" :label="item.name"  :key="item.id">
                        <template slot-scope="scope">
                            {{getProductSkuSp(scope.row,index)}}
                        </template>
                    </el-table-column>
                    <el-table-column label="销售价格" width="100">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.price"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="促销价格" width="100">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.promotionPrice"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品库存" width="100">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.stock"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存预警值" width="100">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.lowStock"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="SKU编号" width="100">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.skuCode"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handleRemoveProductSku(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" style="margin-top: 20px"  @click="handleRefreshProductSkuList">刷新列表</el-button>
                <el-button type="primary" style="margin-top: 20px"  @click="handleSyncProductSkuPrice">同步价格</el-button>
                <el-button type="primary" style="margin-top: 20px"  @click="handleSyncProductSkuStock">同步库存</el-button>
            </el-form-item>

            <el-form-item label="属性图片：" v-if="hasAttrPic">
                <el-card shadow="never" class="cardBg">
                    <div v-for="(item,index) in selectProductAttrPics">
                        <span>{{item.name}}:</span>
                        <single-upload v-model="item.pic" style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>
                    </div>
                </el-card>
            </el-form-item>

            <el-form-item label="商品参数：">
                <el-card shadow="never" class="cardBg">
                    <div v-for="(item,index) in selectProductParam">
                        <div>{{item.name}}:</div>
                        <!-- inputType=1从列表中选取 -->
                        <el-select v-if="item.inputType === 1"  v-model="selectProductParam[index].value">
                            <el-option v-for="item in getParamInputList(item.inputList)" :key="item" :label="item" :value="item">
                            </el-option>
                        </el-select>
                        <el-input v-else v-model="selectProductParam[index].value"></el-input>
                    </div>
                </el-card>
            </el-form-item>
            
            <el-form-item label="商品相册：">
                <MultiUpload v-model="selectProductPics"></MultiUpload>
            </el-form-item>
            
            <el-form-item style="text-align: center;">
                <el-button size="medium" @click="handlePrev">上一步,填写商品促销</el-button>
                <el-button size="medium" type="primary" @click="handleNext">下一步,选择商品关联</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {queryPmsProductAttributeCategoryList,getPmsProductAttributeList} from '@/api/pmsApi'
import MultiUpload from '@/components/upload/MultiUpload'

export default {
    name: "PmsProductAttrDetail",
    components: {
        MultiUpload
    },
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
        return {
            productAttributeCategoryOptions: [],
            //选中的商品属性
            selectProductAttr: [],
            //可手动添加的商品属性
            addProductAttrValue: '',
            //选中的商品属性图片
            selectProductAttrPics: [],
            selectProductParam:[],
            hasEditCreated: false
        }
    },
    computed: {
        // 是否有商品属性图片
        hasAttrPic() {
            if (this.selectProductAttrPics.length < 1) {
                return false;
            }
            return true;
        },
        //商品的编号
        productId(){
            return this.value.id;
        },
        // 商品的主图和画册图片
        selectProductPics: {
            get:function () {
                let pics = [];
                if (this.value.pic === undefined || this.value.pic == null || this.value.pic === '') {
                    return pics;
                }
                pics.push(this.value.pic);
                if (this.value.albumPics === undefined || this.value.albumPics == null || this.value.albumPics === ''){
                    return pics;
                }
                let albumPics = this.value.albumPics.split(',');
                for(let i = 0;i < albumPics.length; i++) {
                    pics.push(albumPics[i]);
                }
                return pics;
            },
            set:function (newValue) {
                if (newValue == null || newValue.length === 0) {
                    this.value.pic = null;
                    this.value.albumPics = null;
                } else {
                    this.value.pic = newValue[0];
                    this.value.albumPics = '';
                    if (newValue.length > 1) {
                        for (let i = 1; i < newValue.length; i++) {
                            this.value.albumPics += newValue[i];
                            if (i !== newValue.length - 1) {
                                this.value.albumPics += ',';
                            }
                        }
                    }
                }
            }
        }
    },
    created() {
        this.getProductAttrCateList();
    },
    watch: {
        productId:function(newValue) {
            if (!this.isEdit) {
                return;
            }
            if (this.hasEditCreated) {
                return;
            }
            if (newValue === undefined || newValue == null || newValue === 0) {
                return;
            }
            this.handleEditCreated();
        }
    },
    methods: {
        handleEditCreated() {
            // 根据商品分类id获取属性和参数
            if(this.value.productAttributeCategoryId != null) {
                this.handleProductAttrChange(this.value.productAttributeCategoryId);
            }
            this.hasEditCreated = true;
        },
        // 查询商品属性分类
        getProductAttrCateList() {
            let param = {}
            queryPmsProductAttributeCategoryList(param).then(response => {
                let list = response.data;
                this.productAttributeCategoryOptions = [];
                for(let i = 0; i < list.length; i++) {
                    this.productAttributeCategoryOptions.push({
                        label: list[i].name,
                        value: list[i].id
                    })
                }
            })
        },
        // 处理产品属性变化
        handleProductAttrChange(value) {
            this.getProductAttrList(0, value);
            this.getProductAttrList(1, value);
        },
        // 查询商品属性列表
        getProductAttrList(type, cid) {
            let param = {type: type}
            getPmsProductAttributeList(cid, param).then(response => {
                let list = response.data.data;
                console.log(list);
                // 属性
                if (type == 0) {
                    this.selectProductAttr = [];
                    for (let i = 0; i < list.length; i++) {
                        let options = [];
                        let values = [];
                        // 编辑状态
                        if (this.isEdit) {
                            // 编辑状态下获取手动添加属性
                            if (list[i].handAddStatus  === 1) {
                                options = this.getEditAttrOptions(list[i].id);
                            }
                            // 编辑状态下获取选中属性
                            values = this.getEditAttrValues(i);
                        }
                        this.selectProductAttr.push({
                            id: list[i].id,
                            name: list[i].name,
                            handAddStatus: list[i].handAddStatus,
                            inputList: list[i].inputList,
                            values: values,
                            options: options
                        })
                    }
                // 参数
                } else {
                    this.selectProductParam = [];
                    for (let i = 0; i < list.length; i++) {
                        let value=null;
                        if(this.isEdit){
                            //编辑模式下获取参数属性
                            value= this.getEditParamValue(list[i].id);
                        }
                        this.selectProductParam.push({
                            id: list[i].id,
                            name: list[i].name,
                            value: value,
                            inputType: list[i].inputType,
                            inputList: list[i].inputList
                        });
                    }
                }
            });
        },
        //获取属性的值
        getEditParamValue(id){
            for(let i=0;i<this.value.productAttributeValueList.length;i++){
                if(id===this.value.productAttributeValueList[i].productAttributeId){
                    return this.value.productAttributeValueList[i].value;
                }
            }
        },
        getProductSkuSp(row, index) {
            let spData = JSON.parse(row.spData);
            if(spData != null && index < spData.length) {
                return spData[index].value;
            } else{
                return null;
            }
        },
        // 根据属性id,获取已选择的属性值,放入到options中返回
        getEditAttrOptions(id) {
            let options = [];
            for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
                let attrValue = this.value.productAttributeValueList[i];
                if (attrValue.productAttributeId === id) {
                    let strArr = attrValue.value.split(',');
                    for (let j = 0; j < strArr.length; j++) {
                        options.push(strArr[j]);
                    }
                    break;
                }
            }
            return options;
        },

        //获取选中的属性值
        getEditAttrValues(index) {
            let values = new Set();
            if (index === 0) {
                for (let i = 0; i < this.value.skuStockList.length; i++) {
                    let sku = this.value.skuStockList[i];
                    let spData = JSON.parse(sku.spData);
                    if (spData!= null && spData.length>=1) {
                        values.add(spData[0].value);
                    }
                }
            } else if (index === 1) {
                for (let i = 0; i < this.value.skuStockList.length; i++) {
                    let sku = this.value.skuStockList[i];
                    let spData = JSON.parse(sku.spData);
                    if (spData!= null && spData.length >= 2) {
                        values.add(spData[1].value);
                    }
                }
            } else {
                for (let i = 0; i < this.value.skuStockList.length; i++) {
                    let sku = this.value.skuStockList[i];
                    let spData = JSON.parse(sku.spData);
                    if (spData!= null && spData.length>=3) {
                        values.add(spData[2].value);
                    }
                }
            }
            return Array.from(values);
        },
        getInputListArr(inputList) {
            return inputList.split(',');
        },
        getParamInputList(inputList) {
            return inputList.split(',');
        },
        // 删除属性值
        handleRemoveProductAttrValue(idx, index) {
            this.selectProductAttr[idx].options.splice(index, 1);
        },
        // 添加属性值
        handleAddProductAttrValue(idx) {
            let options = this.selectProductAttr[idx].options;
            if (this.addProductAttrValue == null || this.addProductAttrValue == '') {
                this.$message({
                    message: '属性值不能为空',
                    type: 'warning',
                    duration: 1000
                });
                return
            }
            if (options.indexOf(this.addProductAttrValue) != -1) {
                this.$message({
                    message: '属性值不能重复',
                    type: 'warning',
                    duration: 1000
                });
                return;
            }
            this.selectProductAttr[idx].options.push(this.addProductAttrValue);
            this.addProductAttrValue = null;
        },
        handleRemoveProductSku(index, row) {
            let list = this.value.skuStockList;
            if (list.length === 1) {
                list.pop();
            } else {
                list.splice(index, 1);
            }
        },
        // 刷新sku列表
        handleRefreshProductSkuList() {
            this.refreshProductSkuList();
        },
        // 刷新商品sku本地缓存列表
        refreshProductSkuList() {
            this.value.skuStockList = [];
            let skuList = this.value.skuStockList;
            //sku是各种属性的交叉
            if (this.selectProductAttr.length === 1) {
                let attr = this.selectProductAttr[0];
                for (let i = 0; i < attr.values.length; i++) {
                    skuList.push({
                        spData: JSON.stringify([{key:attr.name, value:attr.values[i]}])
                    });
                }
            } else if (this.selectProductAttr.length === 2) {
                let attr0 = this.selectProductAttr[0];
                let attr1 = this.selectProductAttr[1];
                for (let i = 0; i < attr0.values.length; i++) {
                    if (attr1.values.length === 0) {
                        skuList.push({
                            spData: JSON.stringify([{key:attr0.name, value:attr0.values[i]}])
                        });
                        continue;
                    }
                    for (let j = 0; j < attr1.values.length; j++) {
                        let spData = [];
                        spData.push({key:attr0.name,value:attr0.values[i]});
                        spData.push({key:attr1.name,value:attr1.values[j]});
                        skuList.push({spData: JSON.stringify(spData)});
                    }
                }  
            } else {
                let attr0 = this.selectProductAttr[0];
                let attr1 = this.selectProductAttr[1];
                let attr2 = this.selectProductAttr[2];
                for (let i = 0; i < attr0.values.length; i++) {
                    if (attr1.values.length === 0) {
                        skuList.push({
                            spData: JSON.stringify([{key:attr0.name,value:attr0.values[i]}])
                        });
                        continue;
                    }
                    for (let j = 0; j < attr1.values.length; j++) {
                        if (attr2.values.length === 0) {
                            let spData = [];
                            spData.push({key:attr0.name,value:attr0.values[i]});
                            spData.push({key:attr1.name,value:attr1.values[j]});
                            skuList.push({
                            spData: JSON.stringify(spData)
                            });
                            continue;
                        }
                        for (let k = 0; k < attr2.values.length; k++) {
                            let spData = [];
                            spData.push({key:attr0.name,value:attr0.values[i]});
                            spData.push({key:attr1.name,value:attr1.values[j]});
                            spData.push({key:attr2.name,value:attr2.values[k]});
                            skuList.push({
                            spData: JSON.stringify(spData)
                            });
                        }
                    }
                }
            }
        },
        // 同步sku价格(同步第一行填写的)
        handleSyncProductSkuPrice() {
            // if(this.value.skuStockList !== null && this.value.skuStockList.length > 0) {
            //     let tempSkuList = [];
            //     tempSkuList = tempSkuList.concat(tempSkuList,this.value.skuStockList);
            //     let price = this.value.skuStockList[0].price;
            //     for(let i = 0; i < tempSkuList.length; i++) {
            //         tempSkuList[i].price = price;
            //     }
            //     this.value.skuStockList = [];
            //     this.value.skuStockList = this.value.skuStockList.concat(this.value.skuStockList,tempSkuList);
            //     console.log(this.value.skuStockList);
            // }


            if(this.value.skuStockList!==null&&this.value.skuStockList.length>0){
            let tempSkuList = [];
            tempSkuList = tempSkuList.concat(tempSkuList,this.value.skuStockList);
            let price=this.value.skuStockList[0].price;
            for(let i=0;i<tempSkuList.length;i++){
              tempSkuList[i].price=price;
            }
            this.value.skuStockList=[];
            this.value.skuStockList=this.value.skuStockList.concat(this.value.skuStockList,tempSkuList);
          }


        },
        // 同步sku库存(同步第一行填写的)
        handleSyncProductSkuStock() {
            if(this.value.skuStockList !== null && this.value.skuStockList.length > 0) {
                let tempSkuList = [];
                tempSkuList = tempSkuList.concat(tempSkuList,this.value.skuStockList);
                let stock = this.value.skuStockList[0].stock;
                let lowStock = this.value.skuStockList[0].lowStock;
                for(let i = 0; i < tempSkuList.length; i++) {
                tempSkuList[i].stock = stock;
                tempSkuList[i].lowStock = lowStock;
                }
                this.value.skuStockList=[];
                this.value.skuStockList=this.value.skuStockList.concat(this.value.skuStockList,tempSkuList);
            }
        },
        // 上一个步骤
        handlePrev() {
            this.$emit('prevStep')
        },
        // 下一个步骤
        handleNext() {
            this.mergeProductAttrValue();
            this.mergeProductAttrPics();
            this.$emit('nextStep')
        },
        // 合并商品属性
        mergeProductAttrValue() {
            this.value.productAttributeValueList = [];
            for (let i = 0; i < this.selectProductAttr.length; i++) {
                let attr = this.selectProductAttr[i];
                // 该属性可手动添加并且有值
                if (attr.handAddStatus === 1 && attr.options != null && attr.options.length > 0) {
                    this.value.productAttributeValueList.push({
                        productAttributeId: attr.id,
                        value: this.getOptionStr(attr.options)
                    })
                }
            }
            for (let i = 0; i < this.selectProductParam.length; i++) {
                let param = this.selectProductParam[i];
                this.value.productAttributeValueList.push({
                    productAttributeId: param.id,
                    value: param.value
                });
            }
        },
        // 合并商品属性图片
        mergeProductAttrPics() {
            for (let i = 0; i < this.selectProductAttrPics.length; i++) {
                for (let j = 0; j < this.value.skuStockList.length; j++) {
                    let spData = JSON.parse(this.value.skuStockList[j].spData);
                    if (spData[0].value === this.selectProductAttrPics[i].name) {
                        this.value.skuStockList[j].pic = this.selectProductAttrPics[i].pic;
                    }
                }
            }
        },
        getOptionStr(arr) {
            let str = '';
            for (let i = 0; i < arr.length; i++) {
                str += arr[i];
                if (i != arr.length - 1) {
                    str += ',';
                }
            }
            return str;
        },



    }
}
</script>

<style scoped>
    .form-inner-container{
        text-align: left;
    }
</style>